#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>	//字节序转换函数
#include<netinet/in.h>	//ipv4地址结构定义头文件
#include<unistd.h>

void error_die(char *msg)
{
	perror(msg);
	exit(1);
}

int main ()
{
	char buf[8192], ch;
	int byte;
	int sockfd, i;
	struct sockaddr_in addr;
	int addrlen = sizeof(addr);
	
	addr.sin_family = AF_INET;
	if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.s_addr) != 1) {
		error_die("inet_pton");
	}
	addr.sin_port = htons(8888);
	
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd == -1) {
		error_die("sockfd");
	}
	
	if (connect(sockfd, (struct sockaddr*)&addr, addrlen) == -1) {
		error_die("connect");
	}
	printf("connect successfully...\n");
	
	sprintf(buf, "GET / HTTP/1.0\r\n\r\n");
	if (write(sockfd, buf, sizeof(buf)) < 0)
		error_die("write");
	while (read(sockfd, buf, sizeof(buf)) > 0) {
		printf("recieve:\n");
		printf("%s", buf);
	}
	
#if 0
	while (1) {
		scanf("%s", buf);
		if (strcmp(buf, "#") == 0) {
			close(sockfd);
			_exit(EXIT_SUCCESS);
		}

		i = strlen(buf);
		if (write(sockfd, buf, i+1) == -1) {
			error_die("write");
		}

		i = read(sockfd, buf, 1023);
		if (i == -1){
			error_die("read");
		}
		printf("%s\n",buf); 

	}
#endif
	close(sockfd);
	_exit(EXIT_SUCCESS);
}
